<template>
  <el-dialog
    ref="dialogRef"
    v-model="dialogVisible"
    :title="title"
    width="550px"
    append-to-body
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="formData.roleName" class="input" placeholder="请输入角色名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="closeDialog()">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, useTemplateRef, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { roleApi } from '@/api'
import type { FormInstance } from 'element-plus'
import { SysRole } from '@/api/system/roleTyppe'

// Props定义
interface Props {
  visible: boolean
  role: SysRole
  title: string
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  role: () => ({ roleId: '', roleName: '' }),
  title: '新增角色'
})

watch(
  () => props.role,
  (newVal) => {
    formData.roleId = newVal.roleId
    formData.roleName = newVal.roleName
  }
)

// Emits定义
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
}>()

// 表单实例
const formRef = useTemplateRef<FormInstance>('formRef')

// 对话框引用
const dialogRef = ref()

// 表单数据
const formData = reactive<SysRole>({
  roleId: '',
  roleName: ''
})

// 表单校验规则
const rules = reactive({
  roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
})

// 对话框显示状态双向绑定
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

onMounted(() => {
  formData.roleId = props.role.roleId
  formData.roleName = props.role.roleName
})

// 提交表单
const submitForm = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      saveRole()
    }
  })
}

// 关闭对话框
const closeDialog = () => {
  resetForm()
  dialogVisible.value = false
}

// 重置表单
const resetForm = () => {
  formData.roleId = ''
  formData.roleName = ''
}

/** 保存角色 */
const saveRole = () => {
  roleApi
    .saveRole(formData)
    .then((res: any) => {
      emit('refresh')
      closeDialog()
      ElMessage.success('保存角色成功')
    })
    .catch((err) => {
      ElMessage.error(err || '保存角色失败')
    })
}

// 提供方法给父组件调用
defineExpose({
  resetForm,
  dialogRef
})
</script>

<style scoped lang="less">
.input {
  width: 150px;
}
</style>
